package org.repo.ant.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.FileSet;
import org.repo.ant.registry.RepoRegistry;

public class Util {
	
	public static FileSet setupRepoJarFileSet(Project project, String repo, String repoBase, String repoDirectory, String repoIncludesFile, String repoExcludesFile){
		RepoRegistry.get().setRepo(repo, repoBase);
		
		FileSet repoJarFileSet = new FileSet();
		repoJarFileSet.setProject(project);
		repoJarFileSet.setDir(RepoRegistry.get().getRepoPath(repo, repoDirectory));
					
		if(repoIncludesFile!=null){
			System.out.println("Including only repo jars from file '" + repoIncludesFile + "' in the build");
			repoJarFileSet.setIncludesfile(new File(repoIncludesFile));
		}
		else if(repoExcludesFile!=null){
			System.out.println("Excluding repo jars from file '" + repoExcludesFile + "' in the build");
			repoJarFileSet.setExcludesfile(new File(repoExcludesFile));
		}
		else{
			System.out.println("Including all repo jars in the build");
			repoJarFileSet.setIncludes("**/*.jar");
		}
		return repoJarFileSet;
	}

	public static List<String> readLines(String file) throws IOException {
		List<String> lines = new ArrayList<String>();
		if(file!=null){
			File f = new File(file);
			BufferedReader br = new BufferedReader(new FileReader(f));
			String line;
			while ((line = br.readLine()) != null) {
				lines.add(line);
			}
			
			br.close();
		}
		return lines;
	}

	public static void copy(File source, File targetDir) {
		try {
			File target = new File(targetDir, source.getName());
			if (target.exists()) {
				target.delete();
			}

			InputStream in = new FileInputStream(source);
			OutputStream out = new FileOutputStream(target);

			int availableLength = in.available();
			byte[] totalBytes = new byte[availableLength];
			in.read(totalBytes);
			out.write(totalBytes);

			/*
			 * byte[] buffer = new byte[1024];
			 * 
			 * int length; // copy the file content in bytes while ((length =
			 * in.read(buffer)) > 0) { out.write(buffer, 0, length); }
			 */

			in.close();
			out.close();
			System.out.println("File copied from " + source + " to " + target);

		}
		catch (Throwable t) {
			t.printStackTrace();
		}
	}

}
